package cn.jflow.boot.web;

import bp.web.UserContextHolder;
import bp.web.WebUser;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Populate per-request user context from legacy storages (Redis / Cookie / Session),
 * and clear it after request completion.
 */
public class UserContextInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // Allow CORS preflight without any work.
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        Map<String,String> ctx = WebUser.buildContextFromRequest();
        if (ctx != null && !ctx.isEmpty()) {
            UserContextHolder.set(ctx);
        } else {
            UserContextHolder.clear();
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContextHolder.clear();
    }
}
